package world;

import java.util.HashSet;
import java.util.Observable;
import java.util.Observer;

import network.MCConnection;
import packets.SPacket;
import packets.s2cpackets.S0x14;

import entities.Player;
import exceptions.MCConnectionException;


/**
 * The playermanager will keep track of the logged in players.
 */
public class PlayerManager extends WorldStateMonitor implements Observer {

	private HashSet<Player> players = new HashSet<Player>();
	
	public PlayerManager(WorldState state) {
		super(state);
	}

	@Override
	public void update(Observable o, Object arg) {
		// TODO Auto-generated method stub
	}

	
	/**
	 * To be called once the player has succesfully logged in.
	 * It will start sending all nececariy post-login data to
	 * the player.
	 * @throws MCConnectionException 
	 */
	public void registerPlayer(Player player) throws MCConnectionException {
		this.players.add(player);
		player.addObserver(this);
		
		/**
		 * Send packet to all others
		 */
		sendOthersToOne(player);
		sendToOthers(player);
		
		state.chatmanager().newMessage(player.getName() + " joined the game.");
	}

	
	/**
	 * To be called once the player has left the server.
	 * It will start sending all nececariy instructions to the other players
	 * in order to remove this player.
	 */
	public void deregisterPlayer(Player player) {
		player.deleteObserver(this);
		this.players.remove(player);
		
		state.chatmanager().newMessage(player.getName() + " disconnected.");
	}
	
	
	
	
	/**

	 * 
	 * @param playerconnection Player to send all other known entities to.
	 * @throws MCConnectionException 
	 */
	private void sendOthersToOne(Player player) throws MCConnectionException {
		for(Player otherplayer : players) {
			if(otherplayer != player) {
				SPacket p = new S0x14(otherplayer);
				getWorldState().connectionManager().sendPacketTo(player, p);
			}
		}
	}
	
	/**
	 * Informs all players that onther player (object) has joined the server.
	 * Its initial state is sent to all others.
	 * 
	 * @param player Connected player which will be added to all logged in player.
	 */
	private void sendToOthers(Player player) {
		SPacket p = new S0x14(player);
		getWorldState().connectionManager().sendPacketToAllOthers(p, player);
	}


	
}
